<template>
  <div>
    <!--面包屑区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--警告提示-->
    <el-alert
      title="注意：只允许为第三级分类设置相关参数！"
      type="warning" :closable="false" show-icon>
    </el-alert>

    <!--选择商品分类-->
    <el-row class="cate-opt">
      <el-col>
        <span>选择商品分类:</span>
        <el-cascader
          v-model="selectedCateKeys"
          :options="cateList"
          :props="cascaderProps"
          @change="handleCateKeysChange"></el-cascader>
      </el-col>
    </el-row>

    <!--内容区-->
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <!--动态参数面板区-->
      <el-tab-pane label="动态参数" name="many">
        <el-row>
          <el-col>
            <el-button type="primary" size="mini" :disabled="!addButtonVisible" @click="addDialogVisible = true">添加参数
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="manyTableData" border stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-tag type="primary" closable
                      v-for="item in scope.row.attr_vals" :key="item"
                      @close="removeAttrVal(scope.row, item)">
                {{item}}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditDialog(scope.row)">编辑
              </el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParam(scope.row.attr_id)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!--静态参数面板区-->
      <el-tab-pane label="静态参数" name="only">
        <el-row>
          <el-col>
            <el-button type="primary" size="mini" :disabled="!addButtonVisible" @click="addDialogVisible = true">静态参数
            </el-button>
          </el-col>
        </el-row>

        <el-table :data="onlyTableData" border stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-tag type="primary" v-for="item in scope.row.attr_vals"
                      closable
                      @close="removeAttrVal(scope.row, item)"
                      :key="item">
                {{item}}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)">
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" @click="openEditDialog(scope.row)" size="mini">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" @click="deleteParam(scope.row.attr_id)" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!--新增对话框-->
    <el-dialog
      :title="'添加' + addDialogTitle"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="handleAddDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParam">确 定</el-button>
  </span>
    </el-dialog>

    <!--编辑对话框-->
    <el-dialog
      :title="'编辑' + addDialogTitle"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="handleEditDialogClose">
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParam">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
        data() {
            return {
                cateList: [],
                selectedCateKeys: [],
                cascaderProps: {
                    expandTrigger: 'hover',
                    label: 'cat_name',
                    value: 'cat_id',
                    children: 'children'
                },
                activeName: 'many',
                onlyTableData: [],
                manyTableData: [],
                addDialogVisible: false,
                addForm: {
                    attr_name: ''
                },
                addFormRules: {
                    attr_name: [
                        {required: true, message: '请输入参数名称', trigger: 'blur'}
                    ],
                },
                editDialogVisible: false,
                editForm: {
                    attr_id: '',
                    attr_name: ''
                },
                addFormRules: {
                    attr_name: [
                        {required: true, message: '请输入参数名称', trigger: 'blur'}
                    ],
                },
                inputVisible: false,
                inputValue: '',
            }
        },
        computed: {
            cat_id() {
                if (this.selectedCateKeys.length === 3) {
                    return this.selectedCateKeys[2]
                }
                return ''
            },
            addDialogTitle() {
                if (this.activeName === 'only') {
                    return '静态参数'
                }
                return '动态参数'
            },
            addButtonVisible() {
                if (this.selectedCateKeys.length === 3) {
                    return true
                }
                return false
            }
        },
        created() {
            this.getCateList()
        },
        methods: {
            async getCateList() {
                const {data: res} = await this.$http.get('categories')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取分类列表失败')
                }
                this.cateList = res.data
                // console.log(this.cateList);
            },
            // 当选择商品分类发生改变时触发
            handleCateKeysChange() {
                if (this.selectedCateKeys.length !== 3) {
                    this.onlyTableData = []
                    this.manyTableData = []
                    this.selectedCateKeys = []
                    return
                }
                // console.log(this.selectedCateKeys);
                this.getParamsList()

            },
            // 点击tab时触发
            handleTabClick() {
                // console.log(this.activeName)
                if (this.cat_id) {
                    this.getParamsList()
                }
            },
            async getParamsList() {
                // [only,many]
                const {data: res} = await this.$http.get(`categories/${this.cat_id}/attributes`, {
                    params: {
                        sel:
                        this.activeName
                    }
                })
                if (res.meta.status !== 200) {
                    return this.$message.error('获取参数列表失败！')
                }
                res.data.forEach(cate => {
                    cate.attr_vals = cate.attr_vals ? cate.attr_vals.split(' ') : []
                    cate.inputVisible = false
                    cate.inputValue = ''
                })
                // console.log(res.data);
                if (this.activeName === 'only') {
                    this.onlyTableData = res.data
                } else {
                    this.manyTableData = res.data
                }

            },
            // 处理新增对话框关闭
            handleAddDialogClose() {
                this.$refs.addFormRef.resetFields()
            },
            addParam() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) {
                        this.$message.error('数据校验失败')
                    }
                    const {data: res} = await this.$http.post(`categories/${this.cat_id}/attributes`, {
                        attr_name:
                        this.addForm.attr_name, attr_sel:
                        this.activeName
                    })
                    if (res.meta.status !== 201) {
                        return this.$message.error('创建参数失败！')
                    }

                    this.$message.success('创建分类成功')
                    this.getParamsList()
                    this.addDialogVisible = false
                })
            },
            handleEditDialogClose() {
                this.$refs.editFormRef.resetFields()
            },
            // 打开编辑框
            openEditDialog(paramInfo) {
                this.editForm.attr_id = paramInfo.attr_id
                this.editForm.attr_name = paramInfo.attr_name
                this.editDialogVisible = true
            },
            // 编辑参数
            editParam() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) {
                        return this.$message.error('数据校验失败')
                    }
                    const {data: res} = await
                    this.$http.put(`categories/${this.cat_id}/attributes/${this.editForm.attr_id}`, {attr_name:
                        this.editForm.attr_name, attr_sel: this.activeName})
                    if (res.meta.status !== 200) {
                        return this.$message.error('更新失败!')
                    }
                    this.$message.success('更新成功')
                    this.getParamsList()
                    this.editDialogVisible = false
                })
            },
            // 删除参数
            async deleteParam(attr_id) {
                let confirmResult = await this.$confirm('此操作将永久删除该参数/属性, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                if (confirmResult !== 'confirm') {
                    return this.$message.error('删除取消成功！')
                }
                const {data: res} = await this.$http.delete(`categories/${this.cat_id}/attributes/${attr_id}`)
                if (res.meta.status !== 200) {
                   return  this.$message.error('删除失败')
                }
                this.$message.success('删除成功')
                this.getParamsList()
            },
            // 处理input 内容
            async handleInputConfirm(attrInfo) {
                // 判断input输入框是否有值
                if (attrInfo.inputValue.trim().length > 0) {
                    attrInfo.inputVisible = false
                    console.log(attrInfo.inputValue);
                    attrInfo.attr_vals.push(attrInfo.inputValue)
                    // 将input输入内容清空
                    attrInfo.inputValue = ''
                    // 提交数据库保存
                    this.saveAttrVals(attrInfo)
                } else {
                    attrInfo.inputVisible = ''
                    attrInfo.inputVisible = false
                }
            },
            async saveAttrVals(attrInfo) {
                // 发送新增参数值请求
                const {data: res} = await this.$http.put(`categories/${this.cat_id}/attributes/${attrInfo.attr_id}`, {
                    attr_name: attrInfo.attr_name,
                    attr_sel: this.activeName,
                    attr_vals: attrInfo.attr_vals.join(' ')
                })
                if (res.meta.status !== 200) {
                    return this.$message.error('参数值保存失败')
                }
                this.$message.success('参数值保存成功')
            },
            // 展现input框
            showInput(attrInfo) {
                attrInfo.inputVisible = true
                // 下次渲染成功后回调
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            removeAttrVal(attrInfo, item) {
                attrInfo.attr_vals.splice(attrInfo.attr_vals.indexOf(item), 1);
                // console.log(attrInfo.attr_vals);
                this.saveAttrVals(attrInfo)
            },

        },

    }
</script>

<style scoped>
  .cate-opt {
    margin: 15px 0px;
  }
  .input-new-tag {
    width: 90px;
  }
  .el-tag { margin: 5px}
</style>
